package com.dms.modules.merchant.service.impl;

import com.dms.common.exception.BusinessException;
import com.dms.common.security.JwtTokenProvider;
import com.dms.modules.merchant.dto.MerchantLoginRequest;
import com.dms.modules.merchant.dto.MerchantLoginResponse;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.service.MerchantAuthService;
import com.dms.modules.merchant.service.MerchantService;
import com.dms.modules.system.service.RoleUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MerchantAuthServiceImpl implements MerchantAuthService {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private RoleUserService userRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    private static final int MERCHANT_USER_TYPE = 2;

    @Override
    public MerchantLoginResponse login(MerchantLoginRequest request) {
        // 验证商家账号
        Merchant merchant = merchantService.getByUsername(request.getUsername());
        if (merchant == null) {
            throw new BusinessException("商家账号不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), merchant.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 验证商家状态
        if (merchant.getStatus() != 1) {
            throw new BusinessException("商家账号已被禁用");
        }

        // 生成JWT令牌
        String accessToken = jwtTokenProvider.generateMerchantToken(merchant.getId(), merchant.getId());

        // 构建响应
        return MerchantLoginResponse.builder()
                .accessToken(accessToken)
                .tokenType("Bearer")
                .expiresIn(jwtTokenProvider.getAccessTokenExpiration())
                .merchantId(merchant.getId())
                .username(merchant.getUsername())
                .shopName(merchant.getShopName())
                .shopLogo(merchant.getShopLogo())
                .status(merchant.getStatus())
                .build();
    }

    @Override
    public MerchantLoginResponse refreshToken(String refreshToken) {
        if (!jwtTokenProvider.isRefreshToken(refreshToken)) {
            throw new BusinessException("无效的刷新令牌");
        }

        try {
            Long merchantId = jwtTokenProvider.getMerchantIdFromToken(refreshToken);
            if (merchantId == null) {
                throw new BusinessException("无效的商家令牌");
            }

            Merchant merchant = merchantService.getById(merchantId);
            if (merchant == null) {
                throw new BusinessException("商家不存在");
            }

            // 生成新的访问令牌
            String newAccessToken = jwtTokenProvider.generateMerchantToken(merchant.getId(), merchant.getId());

            // 构建响应
            return MerchantLoginResponse.builder()
                    .accessToken(newAccessToken)
                    .tokenType("Bearer")
                    .expiresIn(jwtTokenProvider.getAccessTokenExpiration())
                    .merchantId(merchant.getId())
                    .username(merchant.getUsername())
                    .shopName(merchant.getShopName())
                    .shopLogo(merchant.getShopLogo())
                    .status(merchant.getStatus())
                    .build();

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("刷新令牌失败", e);
            throw new BusinessException("刷新令牌失败：" + e.getMessage());
        }
    }

    @Override
    public Merchant getUserInfo(String token) {
        try {
            Long merchantId = jwtTokenProvider.getMerchantIdFromToken(token);
            if (merchantId == null) {
                throw new BusinessException("无效的商家令牌");
            }
            return merchantService.getById(merchantId);
        } catch (Exception e) {
            log.error("获取商家信息失败", e);
            throw new BusinessException("获取商家信息失败：" + e.getMessage());
        }
    }

    @Override
    public void logout(String token) {
        // 由于使用 JWT，服务端不需要做任何处理
        // 客户端需要自行删除存储的令牌
    }
} 